"""
Case Type   : cm_ctl
Case Name   : cm_ctl在主节点修改所有节点的参数值event_triggers,reload方式生效
Create At   : 2023/04/24
Owner       : opentestcase012
Description :
    1.在所有节点创建文件并写入内容,赋给文件执行权限;
    2.在主节点执行,修改所有节点的参数值,reload生效;
    3.重启数据库;
    4.查看cm_agent下的system_call-current.log日志;
    5.恢复参数值并执行reload生效;
Expect      :
    1.创建成功
    2.参数值修改成功
    3.重启成功
    4.所有节点日志中打印this is event_triggers_sh contents
    5.恢复成功
History     :
"""
import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro

primary_sh = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != primary_sh.get_node_num(), '非1+2环境不执行')
class DefinedResource(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)} start----')
        self.common = Common()
        self.pri_user = Node('PrimaryDbUser')
        self.primary_sh = primary_sh
        self.triggers_file = os.path.join(macro.DB_MY_PATH,
                                          'event_triggers.sh')
        self.new_log = os.path.join(macro.CMA_LOG_PATH,
                                    os.path.basename(__file__)[-29:-3])

        text = '----查看agent参数log_dir的默认值; expect:成功----'
        self.log.info(text)
        cm_ctl_res = self.primary_sh.exec_cm_ctl(
            'list', '--param --agent | grep log_dir')
        self.assertIsNotNone(cm_ctl_res, '执行失败:' + text)
        self.default_value = cm_ctl_res.splitlines()[0].split('=')[1].strip()
        self.log.info(self.default_value)

        text = '----修改cm_agent日志目录; expect:成功----'
        self.log.info(text)
        cm_ctl_res = self.primary_sh.exec_cm_ctl_set(
            'agent', f'log_dir="\'{self.new_log}\'"', mode='restart')
        self.assertTrue(cm_ctl_res, '执行失败:' + text)

    def test_cm(self):
        text = '----step1:在所有节点创建文件并写入内容,赋给文件执行权限; expect:成功----'
        self.log.info(text)
        cmd = f"echo 'echo this is event_triggers_sh contents' " \
            f"> {self.triggers_file};" \
            f"chmod +x {self.triggers_file};"
        cm_ctl_res3 = self.primary_sh.exec_gs_ssh(cmd)
        self.assertIn('Successfully execute command on all nodes', cm_ctl_res3,
                      "执行失败:" + text)

        text = '----查看cm_agent日志中triggers日志; expect:成功'
        self.log.info(text)
        grep_cmd = f"cd {self.new_log};" \
            f"grep -c 'this is event_triggers_sh contents' system_call-*"
        grep_res = self.primary_sh.exec_gs_ssh(grep_cmd)
        self.assertEqual('0', grep_res.splitlines()[-6].strip(),
                         "执行失败:" + text)
        self.assertEqual('0', grep_res.splitlines()[-4].strip(),
                         "执行失败:" + text)
        self.assertEqual('0', grep_res.splitlines()[-2].strip(),
                         "执行失败:" + text)

        text = '----step2:在主节点执行,修改所有节点的参数值,reload生效; expect:执行成功----'
        self.log.info(text)
        cmd = f"source {macro.DB_ENV_PATH};" \
            f"cm_ctl set --param --agent -k " \
            f"event_triggers='{{{{\"on_start\":\"{self.triggers_file}\"}}}}';" \
            f"cm_ctl reload --param --agent"
        self.log.info(cmd)
        res = self.common.get_sh_result(self.pri_user, cmd)
        self.assertEqual(2, res.count('success'), "执行失败:" + text)

        text = '----step3:重启数据库; expect:成功----'
        self.log.info(text)
        cm_ctl_res = self.primary_sh.restart_cm_cluster()
        self.assertTrue(cm_ctl_res, '执行失败:' + text)

        text = '----step4:查看cm_agent下的system_call日志; expect:' \
               '所有节点日志中打印this is event_triggers_sh contents----'
        self.log.info(text)
        grep_cmd = f"cd {self.new_log};" \
            f"grep -c 'this is event_triggers_sh contents' system_call-*"
        grep_res = self.primary_sh.exec_gs_ssh(grep_cmd)
        self.assertGreaterEqual(grep_res.splitlines()[-5].strip(), '1',
                                "执行失败:" + text)
        self.assertGreaterEqual(grep_res.splitlines()[-3].strip(), '1',
                                "执行失败:" + text)
        self.assertGreaterEqual(grep_res.splitlines()[-1].strip(), '1',
                                "执行失败:" + text)

    def tearDown(self):
        self.log.info('-----清理环境-----')
        text1 = '----step5:恢复参数值并执行reload生效; expect:成功----'
        self.log.info(text1)
        cmd = f"source {macro.DB_ENV_PATH};" \
            "cm_ctl set --param --agent -k event_triggers='{{}}';" \
            f"cm_ctl reload --param --agent"
        self.log.info(cmd)
        cm_ctl_res1 = self.common.get_sh_result(self.pri_user, cmd)

        text2 = '----修改cm_agent日志目录; expect:成功----'
        self.log.info(text2)
        cm_ctl_res2 = self.primary_sh.exec_cm_ctl_set(
            'agent', f'log_dir="\'{macro.CMA_LOG_PATH}\'"', mode='restart')

        text3 = '----删除sh文件; expect:成功----'
        self.log.info(text3)
        cm_ctl_res3 = self.primary_sh.exec_gs_ssh(
            f'rm -rf {self.triggers_file} {self.new_log}')

        self.assertEqual(2, cm_ctl_res1.count('success'), "执行失败:" + text1)
        self.assertTrue(cm_ctl_res2, '执行失败:' + text2)
        self.assertIn('Successfully execute command on all nodes', cm_ctl_res3,
                      "执行失败:" + text3)
        self.log.info(f'----{os.path.basename(__file__)} finish----')
